package com.hy.frame.widget

import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.hy.frame.R


/**
 * title 自动按比例缩放
 * author heyan
 * time 19-1-21 下午12:12
 * desc 无
 */
class AutoFrameLayout : FrameLayout {

    //缩放比例
    private var ratio = 1f

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        val a = context.obtainStyledAttributes(attrs, R.styleable.AutoFrameLayout, defStyleAttr, 0)
        val ratioWidth = a.getInt(R.styleable.AutoFrameLayout_aflRatioWidth, context.resources.displayMetrics.widthPixels).toFloat()
        ratio = context.resources.displayMetrics.widthPixels.toFloat() / ratioWidth
        a.recycle()
    }


    private fun getRatioSize(number: Int): Int {
        return (number.toFloat() * ratio).toInt()
    }

    override fun addView(child: View?, index: Int, params: ViewGroup.LayoutParams?) {
        var newParams = params
        if (newParams == null)
            newParams = generateDefaultLayoutParams()
        if (newParams!!.width > 0) {
            newParams.width = getRatioSize(newParams.width)
        }
        if (newParams.height > 0) {
            newParams.height = getRatioSize(newParams.height)
        }
        if (newParams is MarginLayoutParams) {
            if (newParams.leftMargin > 0) {
                newParams.leftMargin = getRatioSize(newParams.leftMargin)
            }
            if (newParams.topMargin > 0) {
                newParams.topMargin = getRatioSize(newParams.topMargin)
            }
            if (newParams.rightMargin > 0) {
                newParams.rightMargin = getRatioSize(newParams.rightMargin)
            }
            if (newParams.bottomMargin > 0) {
                newParams.bottomMargin = getRatioSize(newParams.bottomMargin)
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                if (newParams.marginStart > 0) {
                    newParams.marginStart = getRatioSize(newParams.marginStart)
                }
                if (newParams.marginEnd > 0) {
                    newParams.marginEnd = getRatioSize(newParams.marginEnd)
                }
            }
        }
        super.addView(child, index, newParams)
    }
}